﻿using System;
using System.Windows;

namespace PrismInteractionLack
{
	public partial class MainPage
	{

		/// <summary>
		/// Gets or sets the target content control content value.
		/// </summary>
		private Object ContentOfContentControl
		{
			get
			{
				return ViewHolder.Content;
			}
			set
			{
				ViewHolder.Content = value;
			}
		}


		/// <summary>
		/// The single ViewModel.
		/// </summary>
		private Object ViewModel
		{
			get
			{
				return Application.Current.Resources["ViewModel"];
			}
		}


		public MainPage()
		{
			InitializeComponent();

			// Let's set the first view.
			ContentOfContentControl = ViewControl.SampleView1;
		}


		/// <summary>
		/// It will change the current view.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void ChangeViewButtonClick(object sender, RoutedEventArgs e)
		{
			if (ContentOfContentControl != ViewControl.SampleView1)
			{
				ViewControl.SampleView1.DataContext = ViewModel;
				ContentOfContentControl = ViewControl.SampleView1;
			}
			else
			{
				ViewControl.SampleView2.DataContext = ViewModel;
				ContentOfContentControl = ViewControl.SampleView2;
			}
		}

		private void ApplyWorkaroundCheckBoxClicked(object sender, RoutedEventArgs e)
		{
			var isChecked = ApplyWorkaroundCheckBox.IsChecked ?? false;

			if (isChecked)
			{
				SetWorkaround();

				return;
			}

			UnsetWorkaround();
		}

		private void SetWorkaround()
		{
			if (ContentOfContentControl != ViewControl.SampleView1)
			{
				ViewControl.SampleView1.DataContext = null;
			}
			if (ContentOfContentControl != ViewControl.SampleView2)
			{
				ViewControl.SampleView2.DataContext = null;
			}

			ViewControl.SampleView1.WorkaroundOn = true;
			ViewControl.SampleView2.WorkaroundOn = true;
		}

		private void UnsetWorkaround()
		{
			ViewControl.SampleView1.WorkaroundOn = false;
			ViewControl.SampleView2.WorkaroundOn = false;

			RecreateTest();
		}

		private void RecreateTest()
		{
			// Let's recreate the View and ViewModel ties.
			ChangeViewButtonClick(null, null);
			// And set it to the last position.
			ChangeViewButtonClick(null, null);
		}

	}
}
